package com.cheyunkeji.er.fragment.auction;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyunkeji.er.activity.auction.XunJiaDetailActivity;
import com.cheyunkeji.er.adapter.auction.AuctionRecordAdapter;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.MsgCountWrapper;
import com.cheyunkeji.er.bean.auction.AuctionProjectBean;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;

import org.greenrobot.eventbus.EventBus;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Michael on 2017/2/24 10:03.
 */

public class AuctionRecordMine extends BaseFragment implements OnRefreshListener, OnLoadMoreListener, AdapterView.OnItemClickListener {


    //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
    private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;

    //    每页数据量
    private static final int COUNTS_PER_PAGE = 10;

    @BindView(R.id.swipe_target)
    ListView swipeTarget;
    @BindView(R.id.swipe_layout)
    SwipeLayout swipeLayout;
    @BindView(R.id.ll_empty_content)
    LinearLayout llEmptyContentDisplay;


    private int CURRENT_LOAD_PAGE = 1;

    private String TAG = AuctionRecordMine.class.getSimpleName();

    private ArrayList<AuctionProjectBean> dataList;
    private AuctionRecordAdapter adapter;
    private boolean isPrepared ;

    private Handler uiRefreshHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {

                onRefreshSuccessed((ArrayList<AuctionProjectBean>) msg.obj);
            } else {

                onLoadMoreSuccessed((ArrayList<AuctionProjectBean>) msg.obj);
            }
        }
    };


    @Override
    protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
        contentView = inflater.inflate(R.layout.er_frag_auction_on_process, container, false);
        ButterKnife.bind(this, contentView);
    }

    @Override
    protected void init() {
        dataList = new ArrayList<>();
        adapter = new AuctionRecordAdapter(dataList, getActivity(), Constants.AUCTION_TYPE_GOT_MYSELF);
        swipeTarget.setAdapter(adapter);
    }

    @Override
    protected void initView() {

        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setOnLoadMoreListener(this);
        swipeTarget.setOnItemClickListener(this);
    }

    @Override
    protected void initData() {
        isPrepared = true ;
        lazyLoad();
    }

    private void hideEmptyView() {

        //swipeLayout.setVisibility(View.VISIBLE);
        llEmptyContentDisplay.setVisibility(View.INVISIBLE);

    }


    private void showContentEmptyView() {

        //swipeLayout.setVisibility(View.INVISIBLE);
        llEmptyContentDisplay.setVisibility(View.VISIBLE);
    }


    public void loadAuctionList(int page, int rows) {

        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("page", String.valueOf(page));
        params.put("rows", String.valueOf(rows));
        params.put("fcall", String.valueOf(Constants.AUCTION_TYPE_GOT_MYSELF));

        ApiClient.postForm(HttpConstants.AUCTION_LIST, params, new RespCallback<List<AuctionProjectBean>>() {

            @Override
            protected void onRequestFailed(String msg) {

                SToast.show(msg);
            }

            @Override
            protected void onMsgCount(int rows) {
                super.onMsgCount(rows);
                EventBus.getDefault().post(new MsgCountWrapper(rows,Constants.AUCTION_MINE_GOT_PAGE_INDEX ));
            }

            @Override
            protected void onSuccess(List<AuctionProjectBean> data) {

                Log.e(TAG, "onSuccess: " + data.size());
                Log.e(TAG, "onSuccess: CURRENT PAGE INDEX : " + CURRENT_LOAD_PAGE);

                Message msg = uiRefreshHandler.obtainMessage();
                msg.obj = data;
                uiRefreshHandler.sendMessage(msg);

            }

            @Override
            public void onError(Exception e) {
                super.onError(e);

                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                }

                if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                    swipeLayout.endRefresh();
                } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
                    swipeLayout.endLoadMore();
                }
            }

        });

    }

    private void onRefreshSuccessed(ArrayList<AuctionProjectBean> newList) {

        if (newList != null && newList.size() != 0) {

            hideEmptyView();
            dataList.clear();
            dataList.addAll(newList);
            adapter.notifyDataSetChanged();
            CURRENT_LOAD_PAGE++;

        } else if (newList.size() == 0) {
            showContentEmptyView();
            dataList.clear();
            adapter.notifyDataSetChanged();
        }
        swipeLayout.endRefresh();

    }


    /**
     * 上拉加载成功刷新
     *
     * @param newList
     */
    private void onLoadMoreSuccessed(ArrayList<AuctionProjectBean> newList) {

        if (newList != null) {

            if (newList.size() != 0) {

                swipeLayout.endLoadMore();
                dataList.addAll(newList);
                adapter.notifyDataSetChanged();
                CURRENT_LOAD_PAGE++;

            } else {

                swipeLayout.endLoadMore();
                swipeLayout.setLoadMoreEnabled(false);

            }
        }
    }


    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();

        if(!isPrepared || !isVisible) {
            return;
        }

        swipeLayout.setRefreshing(true);
        onRefresh();
    }

    @Override
    public void onPause() {
        super.onPause();
    }


    @Override
    public void onRefresh() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
        CURRENT_LOAD_PAGE = 1;
        loadAuctionList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE);
        swipeLayout.setLoadMoreEnabled(true);
    }

    @Override
    public void onLoadMore() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
        loadAuctionList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(getActivity(), XunJiaDetailActivity.class);
        intent.putExtra(Constants.DETAIL_RESULT_TYPE,Constants.RESULT_TYPE_AUCTION_GOT);
        intent.putExtra("tid",dataList.get(position).getTid());
        startActivity(intent);
    }

}
